import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';

import { MAT_MOMENT_DATE_FORMATS, MomentDateAdapter } from '@angular/material-moment-adapter';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';

import { UserService } from '../shared/user.service';
import { UserGeneralConfig } from '../../core/config/user-general.config';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';

@Component({
    selector: 'op-search-bar',
    templateUrl: './search-bar.component.html',
    providers: [
        { provide: MAT_DATE_LOCALE, useValue: 'zh-cn-CH' },
        { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
        { provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS }]
})
export class SearchBarComponent implements OnInit {
    @Output() searchData: EventEmitter<any> = new EventEmitter();
    formGroup: FormGroup;
    searchDetails: any;
    statusDetails: any;
    constantOfStatus = UserGeneralConfig.status;
    minEndDate = null;
    maxStartDate = null;
    status: any[] = [];
    filteredStatus: any[];

    constructor(
        private formBuilder: FormBuilder,
        private userService: UserService,
        private router: Router
    ) { }

    ngOnInit(): void {
        this.searchDetails = {
            startDate: null,
            endDate: null,
            userName: [''],
            status: null
        };

        this.filteredStatus = this.status;

        this.createForm();
    }

    onSearch(): void {
        if (this.searchDetails.startDate && typeof (this.searchDetails.startDate) === 'object') {
            this.searchDetails.startDate = this.searchDetails.startDate.format('YYYY-MM-DD');
        }

        if (this.searchDetails.endDate && typeof (this.searchDetails.endDate) === 'object') {
            this.searchDetails.endDate = this.searchDetails.endDate.format('YYYY-MM-DD');
        }

        console.log(this.formGroup.value);

        this.searchData.emit(this.formGroup.value);
    }

    refresh(): void {
        this.minEndDate = null;
        this.maxStartDate = null;

        this.createForm();
        this.searchData.emit(this.searchDetails);
    }

    getStatus(): void {
        if (this.filteredStatus.length < 1) {
            this.formGroup.patchValue({ status: null });
        } else {
            this.formGroup.patchValue({ status: this.filteredStatus[0] });
        }
    }

    add(): void {
        this.router.navigate(['/users-demo/add']);
    }

    minEndDateChange(event): void {
        this.minEndDate = event.format('YYYY-MM-DD');
    }

    maxStartDateChange(event): void {
        this.maxStartDate = event.format('YYYY-MM-DD');
    }
    private createForm(): void {
        this.formGroup = this.formBuilder.group({
            startTime: [''],
            endTime: [''],
            name: [''],
            status: [''],
        });

        this.formGroup.controls.status.valueChanges.pipe(
            debounceTime(1000),
            distinctUntilChanged()
        ).subscribe(result => {
            this.userService.getMatchedStatus({ keyword: result }).subscribe(res => {
                this.status = res.value;
                this.filteredStatus = this.filterStates(result);
            });
        });
    }

    private filterStates(result: string) {
        return this.status.filter(state =>
            state.indexOf(result) >= 0);
    }
}